
const http = require("http");

/**
 * @description: http请求
 * @param {string} method 请求方式
 * @param {string} path 请求路由
 * @param {string} hostname 主机名称
 * @return {object} 结果
 */
let utils = {};
utils.request = async function ({method,path,hostname}) {
    let options = {
        hostname: hostname,
        port: 80,
        path: path,
        method: method,
        headers: {
            'Content-Type': 'application/json'
        }
    };
    let resData = "";
    return new Promise((resolve, reject) => {
        let req = http.request(options, function (res) {
            res.setEncoding('utf8');
            res.on('data', function (chunk) {
                resData += chunk;
            });
            res.on('end', function () {
                resolve({
                    success: true,
                    data: resData,
                    errorCode: "",
                    errorMessage: ""
                });
            });
        });
        req.on('error', function (err) {
            resolve({
                success: false,
                data: {
                    headers: res.headers,
                    data: resData
                },
                errorCode: "500",
                errorMessage: JSON.stringify(err)
            });
        });
        req.end();
    })
    
}

module.exports = exports.utils = utils;
